package com.cplatform.movie.back.sale.web;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cplatform.dbhelp.page.Page;
import com.cplatform.movie.back.avtivities.entity.Activities;
import com.cplatform.movie.back.avtivities.service.ActivitiesService;
import com.cplatform.movie.back.model.SessionUser;
import com.cplatform.movie.back.sale.entity.ItemSale;
import com.cplatform.movie.back.sale.service.ImageDetailService;
import com.cplatform.movie.back.sale.service.ItemSaleService;
import com.cplatform.movie.back.store.service.StoreService;
import com.cplatform.movie.back.sys.dao.SysTypeDao;
import com.cplatform.movie.back.sys.entity.SysType;
import com.cplatform.movie.back.utils.AppConfig;
import com.cplatform.movie.back.utils.JsonRespWrapper;
import com.cplatform.movie.back.utils.LogUtils;
import com.cplatform.util2.TimeStamp;

/**
 * Title. 商品控制层 <br>
 * Description.
 * <p>
 * Author: liuyt
 * <p>
 * Version: 1.0
 * <p>
 */
@Controller
@RequestMapping("/itemsale")
public class ItemSaleController {
	Logger log = Logger.getLogger(ItemSaleController.class);
	@Autowired
	private ItemSaleService itemSaleService;
	@Autowired
	private AppConfig appConfig;
	@Autowired
	private ImageDetailService imageDetailService;
	@Autowired
	private SysTypeDao sysTypeDao;
	@Autowired
	private StoreService storeService;
	@Autowired
	private LogUtils logUtils;
	@Autowired
	private ActivitiesService activitiesService;

	/**
	 * @Title: 进入商品列表页面 <br>
	 * @param itemSale
	 * @param page
	 * @param model
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/list")
	public String list(HttpSession session, ItemSale itemSale, @RequestParam(required = false, value = "page", defaultValue = "1") int page, Model model) {
		Page<ItemSale> pageData = null;
		SessionUser sessionUser = (SessionUser) session.getAttribute(SessionUser.SESSION_USER_KEY);
		try {
			pageData = itemSaleService.list(itemSale, page, sessionUser);
		} catch (SQLException e) {
			log.error("商品列表查询失败:" + e.getMessage());
		}
		model.addAttribute("pageData", pageData);
		model.addAttribute("itemSale", itemSale);
		model.addAttribute("postFlagMap", ItemSale.postFlagMap);
		model.addAttribute("auditStatusMap", ItemSale.auditStatusMap);
		model.addAttribute("saleStatusMap", ItemSale.saleStatusMap);
		return "saleitem/saleitem-list";
	}

	/**
	 * @Title: 进入添加商品页面 <br>
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String addGet(Model model) {
		ItemSale itemSale = new ItemSale();
		model.addAttribute("itemSale", itemSale);
		model.addAttribute("uploadImgId", new Date().getTime());
		model.addAttribute("uploadCoverImgPath", appConfig.getUploadItemCoverPath());
		model.addAttribute("uploadInfoImgPath", appConfig.getUploadItemInfoPath());
		return "saleitem/saleitem-add";
	}

	/**
	 * @Title: 添加商品 <br>
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Object addPost(ItemSale itemSale, HttpServletRequest request, HttpSession session, @RequestParam(value = "acId", required = false) Long acId) {
		try {
			SessionUser sessionUser = (SessionUser) session.getAttribute(SessionUser.SESSION_USER_KEY);
			Long storeId = storeService.findStoreIdByUserCode(sessionUser.getSysUser().getId());
			if (storeId == null) {
				log.error("添加商品失败:" + sessionUser.getSysUser().getUserCode() + "未关联任何商户。");
				return JsonRespWrapper.error("商品添加失败:当前登陆帐号" + sessionUser.getSysUser().getUserCode() + "未关联任何商户。");
			}

			itemSale.setCreateTime(TimeStamp.getTime(TimeStamp.YYYYMMDDhhmmss));
			itemSale.setCreateUserId(sessionUser.getId());
			itemSale.setUpdateTime(TimeStamp.getTime(TimeStamp.YYYYMMDDhhmmss));
			itemSale.setUpdateUserId(sessionUser.getId());
			itemSale.setStatus(0l);
			itemSale.setIsValid(1l);
			itemSale.setSaleStatus(0l);
			itemSale.setStoreId(storeId);
			itemSale.setImgPath(itemSale.getImgPath().replace("N", "N0"));
			// 详情图片
			String[] jzImgIdArray = request.getParameterValues("jzImgId");
			String[] jzImgArray = request.getParameterValues("jzImgPath");
			String[] jzImgOrderArray = request.getParameterValues("orderNum");
			itemSale = itemSaleService.save(itemSale, jzImgArray, jzImgOrderArray, jzImgIdArray);

			// -- 关联活动
			if (itemSale != null) {
				itemSaleService.linkActivities(acId, itemSale.getId());
			}
		} catch (Exception e) {
			log.error("添加商品失败:" + e.getMessage());
			return JsonRespWrapper.error("商品添加失败！");
		}
		logUtils.logAdd("商品管理", "商品添加成功");
		return JsonRespWrapper.success("商品添加成功", "/itemsale/list");
	}

	/**
	 * @Title: 商品分类选择 <br>
	 * @param type
	 * @param selected
	 * @param isone
	 * @param model
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "selectType")
	public String selectType(@RequestParam Long type, @RequestParam(required = false, defaultValue = "") String selected, Model model) {
		List<SysType> typeList = sysTypeDao.findSysType(type);
		model.addAttribute("typeList", typeList);
		model.addAttribute("isone", true);
		model.addAttribute("selected", selected);
		return "saleitem/type_select";
	}

	/**
	 * @Title: 进入商品详情列表 <br>
	 * @param model
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/view/{id}")
	public String view(Model model, @PathVariable Long id) {
		ItemSale itemSale = null;
		String activities[] = null;
		try {
			itemSale = itemSaleService.findById(id);
			activities = itemSaleService.findLinkAcById(id);
		} catch (SQLException e) {
			log.error("进入商品详情列表失败：" + e.getMessage());
		}
		List<Map<String, Object>> imageInfos = imageDetailService.findImageInfoByItemId(id);

		model.addAttribute("postFlagMap", ItemSale.postFlagMap);
		model.addAttribute("auditStatusMap", ItemSale.auditStatusMap);
		model.addAttribute("saleStatusMap", ItemSale.saleStatusMap);
		model.addAttribute("coverImagePath", appConfig.getUploadItemCoverPath());
		model.addAttribute("infoImagePath", appConfig.getUploadItemInfoPath());
		model.addAttribute("itemSale", itemSale);
		model.addAttribute("imageInfos", imageInfos);
		model.addAttribute("activities", activities);
		return "saleitem/saleitem-view";
	}

	/**
	 * @Title: 进入编辑页面 <br>
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String editGet(@PathVariable Long id, Model model) {
		ItemSale itemSale = null;
		String activities[] = null;
		try {
			itemSale = itemSaleService.findById(id);
			activities = itemSaleService.findLinkAcById(id);
		} catch (SQLException e) {
			log.error("进入编辑页面 失败：" + e.getMessage());
		}
		List<Map<String, Object>> imageInfos = imageDetailService.findImageInfoByItemId(id);
		model.addAttribute("itemSale", itemSale);
		model.addAttribute("imageInfos", imageInfos);
		model.addAttribute("activities", activities);
		model.addAttribute("uploadImgId", new Date().getTime());
		model.addAttribute("coverImagePath", appConfig.getUploadItemCoverPath());
		model.addAttribute("infoImagePath", appConfig.getUploadItemInfoPath());
		return "saleitem/saleitem-edit";
	}

	/**
	 * @Title: 商品更新 <br>
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Object editPost(ItemSale itemSale, @PathVariable Long id, Model model, HttpSession session, HttpServletRequest request,
			@RequestParam(value = "acId", required = false) Long acId) {
		try {
			ItemSale item = itemSaleService.findById(id);
			SessionUser sessionUser = (SessionUser) session.getAttribute(SessionUser.SESSION_USER_KEY);
			Long storeId = storeService.findStoreIdByUserCode(sessionUser.getSysUser().getId());
			if (storeId == null) {
				log.error("编辑商品失败:" + sessionUser.getSysUser().getUserCode() + "未关联任何商户。");
				return JsonRespWrapper.error("商品编辑失败:当前登陆帐号" + sessionUser.getSysUser().getUserCode() + "未关联任何商户。");
			}
			item.setUpdateTime(TimeStamp.getTime(TimeStamp.YYYYMMDDhhmmss));
			item.setUpdateUserId(sessionUser.getId());
			item.setStatus(0l); // 未审核
			item.setSaleStatus(0l); // 未上架
			item.setIsValid(1l); // 有效
			item.setName(itemSale.getName()); // 名称
			item.setShortName(itemSale.getShortName()); // 简称
			item.setWarmPrompt(itemSale.getWarmPrompt()); // 温馨提示
			item.setRemark(itemSale.getRemark()); // 商品介绍
			item.setTypeId(itemSale.getTypeId()); // 分类ID
			item.setWeight(itemSale.getWeight()); // 重量
			item.setPostFlag(itemSale.getPostFlag()); // 是否物流
			item.setLogisticsFee(itemSale.getLogisticsFee()); // 物流费用
			item.setSaleStartTime(itemSale.getSaleStartTime()); // 销售开始时间
			item.setSaleStopTime(itemSale.getSaleStopTime()); // 销售结束时间
			item.setUserPerBuyNum(itemSale.getUserPerBuyNum()); // 单个用户购买数量
			item.setStockNum(itemSale.getStockNum()); // 库存
			item.setMarketPrice(itemSale.getMarketPrice()); // 市场价格
			item.setShopPrice(itemSale.getShopPrice()); // 售价

			// -- 封面图片更新
			if (!itemSale.getImgPath().equals(itemSale.getImgPath())) {
				item.setImgPath(itemSale.getImgPath().replace("N", "N0"));
			}

			// 详情图片
			String[] jzImgIdArray = request.getParameterValues("jzImgId");
			String[] jzImgArray = request.getParameterValues("jzImgPath");
			String[] jzImgOrderArray = request.getParameterValues("orderNum");
			itemSaleService.save(item, jzImgArray, jzImgOrderArray, jzImgIdArray);
			
			// -- 关联活动
			if (itemSale != null) {
				itemSaleService.linkActivities(acId, itemSale.getId());
			}

		} catch (Exception e) {
			log.error("商品更新操作失败：" + e.getMessage());
			return JsonRespWrapper.error("商品更新失败");
		}
		List<Map<String, Object>> imageInfos = imageDetailService.findImageInfoByItemId(id);
		model.addAttribute("itemSale", itemSale);
		model.addAttribute("imageInfos", imageInfos);
		model.addAttribute("uploadImgId", new Date().getTime());
		model.addAttribute("coverImagePath", appConfig.getUploadItemCoverPath());
		model.addAttribute("infoImagePath", appConfig.getUploadItemInfoPath());
		logUtils.logModify("商品管理", "商品更新成功");
		return JsonRespWrapper.success("商品更新成功", "/itemsale/list");
	}

	/**
	 * @Title: 进入商品审核页面 <br>
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/audit", method = RequestMethod.GET)
	public String auditGet(@RequestParam Long id, Model model) {
		ItemSale itemSale = null;
		try {
			itemSale = itemSaleService.findById(id);
		} catch (SQLException e) {
			log.error("进入商品审核页面失败：" + e.getMessage());
		}
		model.addAttribute("itemSale", itemSale);
		return "saleitem/saleitem-audit";
	}

	/**
	 * @Title: 商品审核 <br>
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/audit", method = RequestMethod.POST)
	@ResponseBody
	public Object auditPost(@RequestParam(required = true) Long id, @RequestParam(required = true) Long auditSataus, Model model) {
		ItemSale itemSale = null;
		try {
			itemSale = itemSaleService.findById(id);
			itemSale.setStatus(auditSataus);
			itemSaleService.saveOne(itemSale);
		} catch (SQLException e) {
			log.error("商品审核失败：" + e.getMessage());
			return JsonRespWrapper.error("商品审核失败");
		}
		logUtils.logAudit("商品管理", "商品审核成功");
		return JsonRespWrapper.success("商品审核成功", "/itemsale/list");
	}

	/**
	 * @Title: 商品上下架 <br>
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/ruing/{id}/{type}")
	@ResponseBody
	public Object runing(@PathVariable Long id, @PathVariable Long type) {
		ItemSale itemSale = null;
		try {
			itemSale = itemSaleService.findById(id);
			if (type == 1) { // 上架
				itemSale.setSaleStatus(1l);
			} else if (type == 2) {
				itemSale.setSaleStatus(0l);
			}
			itemSaleService.saveOne(itemSale);
		} catch (SQLException e) {
			log.error("上/下架失败：" + e.getMessage());
			return JsonRespWrapper.error("商品上/下架失败");
		}
		logUtils.logOther("商品管理", "商品上/下架成功");
		return JsonRespWrapper.successReload("操作成功");
	}

	/**
	 * @Title: 商品逻辑删除 <br>
	 * @param id
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/delete/{id}")
	@ResponseBody
	public Object delete(@PathVariable Long id, Model model) {
		itemSaleService.delete(id);
		logUtils.logDelete("商品管理", "商品删除成功");
		return JsonRespWrapper.success("商品删除成功", "/itemsale/list");
	}

	/**
	 * @Title: 进入活动列表弹框 <br>
	 * @param ac
	 * @param page
	 * @param model
	 * @return
	 * @throws
	 */
	@RequestMapping("/activities")
	public String list(Activities ac, @RequestParam(required = false, value = "page", defaultValue = "1") int page, Model model) {
		Page<Activities> pageData = null;
		try {
			pageData = activitiesService.listSelect(ac, page);
		} catch (SQLException e) {
			log.error("进入活动列表失败：" + e.getMessage());
		}

		model.addAttribute("pageData", pageData);
		model.addAttribute("ac", ac);
		model.addAttribute("auditStatusMap", Activities.auditStatusMap);
		model.addAttribute("saleStatusMap", Activities.saleStatusMap);
		model.addAttribute("typeMap", Activities.typeMap);
		return "saleitem/activities-select";
	}
}
